package com.newhopegroup.webcommons.context;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 线程级上下文，限定作用于controller的执行过程中，通过Interceptor实现,Servlet用
 * Created by liusen on 15-7-8.
 */

@Component
public class ServletContextUtils extends ContextUtils {

    private final Logger logger = LoggerFactory.getLogger(ServletContextUtils.class);

    public final ThreadLocal<HashMap<String, Object>> context = new ThreadLocal<HashMap<String, Object>>();

    public final String SESSION_ID = "SessionId";
    public final String USER_NAME = "UserName";
    public final String UUID = "UUID";

    /**
     * 设置SessionId
     *
     * @param sessionId
     * @throws ContextException
     */
    public void setSessionId(String sessionId) throws ContextException {
        setContextValue(SESSION_ID, sessionId);
    }

    /**
     * 获取SessionId
     *
     * @throws ContextException
     */
    public String getSessionId() throws ContextException {
        return getContextValue(SESSION_ID).toString();
    }

    /**
     * 设置用户名
     *
     * @param userName
     * @throws ContextException
     */
    public void setUserName(String userName) throws ContextException {
        setContextValue(USER_NAME, userName);
    }

    /**
     * 获取用户名
     *
     * @throws ContextException
     */
    public String getUseName() throws ContextException {
        return getContextValue(USER_NAME).toString();
    }

    /**
     * 设置uuid
     *
     * @param uuid
     * @throws ContextException
     */
    public void setUuid(String uuid) throws ContextException {
        setContextValue(UUID, uuid);
    }

    /**
     * 获取uuid
     *
     * @throws ContextException
     */
    public String getUuid() throws ContextException {
        return getContextValue(UUID).toString();
    }

    @Override
    public String toString() {
        return "ServletContextUtils{" +
                "context=" + ReflectionToStringBuilder.toString(context.get()) +
                '}';
    }
}
